import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router';
import UsersMgmt from '@/views/UsersMgmt.vue';
import Home from '@/views/Home.vue';
import { useUserStore } from '@/stores/user';

// 在路由创建时清除可能存在的无效token
const clearInvalidToken = () => {
  const token = localStorage.getItem('token');
  if (token === '' || token === 'null' || token === 'undefined') {
    console.log('🧹 清除无效token');
    localStorage.removeItem('token');
    localStorage.removeItem('username');
  }
};

// 立即执行清理
clearInvalidToken();

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/users-mgmt',
    name: 'UsersMgmt',
    component: UsersMgmt
  },
  {
    path: '/uom',
    name: 'Uom',
    component: () => import('@/views/Uom.vue')
  },
  {
    path: '/categories1',
    name: 'Categories1',
    component: () => import('@/views/Categories1.vue')
  },
  {
    path: '/categories2',
    name: 'Categories2',
    component: () => import('@/views/Categories2.vue')
  },
  {
    path: '/categories3',
    name: 'Categories3',
    component: () => import('@/views/Categories3.vue')
  },
  {
    path: '/sites',
    name: 'Sites',
    component: () => import('@/views/Sites.vue')
  },
  {
    path: '/damage-report',
    name: 'DamageReport',
    component: () => import('@/views/DamageReport.vue')
  },
  {
    path: '/transfer-items',
    name: 'TransferItems',
    component: () => import('@/views/TransferItems.vue')
  },
  {
    path: '/transfer-request',
    name: 'TransferRequest',
    component: () => import('@/views/TransferRequest.vue')
  },
  {
    path: '/user-roles',
    name: 'UserRoles',
    component: () => import('@/views/UserRoles.vue')
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue')
  },
  {
    path: '/365LoginSuccess',
    name: '365LoginSuccess',
    component: () => import('@/views/365LoginSuccess.vue')
  },
  {
    path: '/test-auth',
    name: 'TestAuth',
    component: () => import('@/views/TestAuth.vue')
  },
  {
    path: '/test-formpost',
    name: 'TestFormPost',
    component: () => import('@/views/TestFormPost.vue')
  },
  {
    path: '/ms-365-auth-error',
    name: 'ms-365-auth-error',
    component: () => import('@/views/ms-365-auth-error.vue')
  },
  {
    path: '/test-actual-login',
    name: 'TestActualLogin',
    component: () => import('@/views/TestActualLogin.vue')
  },
  {
    path: '/error',
    name: 'Error',
    component: () => import('@/views/Error.vue')
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/Error.vue'),
    props: { message: '页面未找到' }
  },
  // 其他页面路由可继续添加
];

const router = createRouter({
  history: createWebHistory(),
  routes
});

router.beforeEach((to, from, next) => {
  console.log('🛡️ 路由守卫检查:', {
    to: to.path,
    from: from.path,
    fullPath: to.fullPath,
    timestamp: new Date().toISOString()
  });
  
  const userStore = useUserStore();
  const publicPages = [ '/login', '/error', '/auth/ms-365-auth/callback', '/test-auth', '/test-formpost', '/365LoginSuccess', '/test-actual-login'];
  const isPublicPage = publicPages.includes(to.path);
  const authRequired = !isPublicPage;
  
  // 检查是否有有效的token
  const hasValidToken = !!userStore.token && userStore.token.trim() !== '';
  
  // 额外检查localStorage中的token
  const localStorageToken = localStorage.getItem('token');
  const hasLocalStorageToken = !!localStorageToken && localStorageToken.trim() !== '';
  
  console.log('🔍 详细认证检查:', {
    isPublicPage,
    authRequired,
    isLogin: userStore.isLogin,
    hasToken: !!userStore.token,
    hasValidToken,
    hasLocalStorageToken,
    token: userStore.token,
    localStorageToken: localStorageToken,
    tokenLength: userStore.token?.length || 0
  });
  
  // 如果页面需要认证但没有有效token，立即重定向
  if (authRequired && !hasValidToken) {
    console.log('🚫 需要认证但未登录，立即重定向到登录页面');
    console.log('📝 重定向详情:', {
      from: to.fullPath,
      to: '/login',
      query: { redirect: to.fullPath }
    });
    
    // 立即重定向，不等待组件加载
    next({ 
      path: '/login',
      query: { redirect: to.fullPath },
      replace: true // 使用replace避免在历史记录中留下当前页面
    });
    return; // 确保不会继续执行
  }
  
  // 如果是登录页面但已经登录，重定向到主页
  if (to.path === '/login' && hasValidToken) {
    console.log('✅ 已登录用户访问登录页面，重定向到主页');
    next({ path: '/', replace: true });
    return;
  }
  
  console.log('✅ 路由检查通过，允许访问');
  next();
});

export default router; 